<template>
  <div class="container">
    <!-- 主菜单 - 默认显示 -->
    <div v-if="!room && step === 'menu'" class="menu-view">
      <h1>🛡️ 阿瓦隆 Avalon</h1>
      <div class="menu-buttons">
        <button @click="showCreateForm" class="menu-btn create-btn">创建房间</button>
        <button @click="showJoinForm" class="menu-btn join-btn">加入房间</button>
        <button @click="showHistory" class="menu-btn history-btn">📜 游戏历史</button>
      </div>
    </div>

    <!-- 游戏历史记录 -->
    <div v-if="!room && step === 'history'" class="history-view">
      <div class="history-header">
        <h2>📜 游戏历史记录</h2>
        <button @click="backToMenu" class="back-btn">返回</button>
      </div>
      <div v-if="loadingHistory" class="loading-container">
        <div class="loading"></div>
        <p>加载历史记录中...</p>
      </div>
      <div v-else-if="gameHistory.length === 0" class="empty-history">
        <p>暂无游戏历史记录</p>
      </div>
      <div v-else class="history-list">
        <div v-for="record in gameHistory" :key="record.id" class="history-item" :class="record.winner === 'good' ? 'good-win' : 'evil-win'" @click="showHistoryDetail(record)">
          <div class="history-item-header">
            <div class="history-winner">
              <span class="winner-icon">{{ record.winner === 'good' ? '🎉' : '💀' }}</span>
              <span class="winner-text">{{ record.winner === 'good' ? '好人胜利' : '坏人胜利' }}</span>
            </div>
            <div class="history-time">{{ formatTime(record.timestamp) }}</div>
          </div>
          <div class="history-item-body">
            <div class="history-stats">
              <span class="stat-item">
                <strong>玩家数：</strong>
                {{ record.playerCount }}人
              </span>
              <span class="stat-item">
                <strong>成功任务：</strong>
                {{ record.successCount }}/5
              </span>
              <span class="stat-item">
                <strong>失败任务：</strong>
                {{ record.failCount }}/5
              </span>
            </div>
            <div class="history-quest-results">
              <div v-for="(result, index) in record.questResults" :key="index" class="history-quest-badge" :class="result ? 'success' : 'fail'">任务{{ index + 1 }}: {{ result ? '✅' : '❌' }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 历史记录详情弹窗 -->
    <div v-if="selectedHistory" class="history-detail-modal" @click.self="closeHistoryDetail">
      <div class="history-detail-content">
        <div class="history-detail-header">
          <h3>游戏详情</h3>
          <button @click="closeHistoryDetail" class="close-btn">×</button>
        </div>
        <div class="history-detail-body">
          <div class="detail-section">
            <h4>游戏结果</h4>
            <div class="detail-winner" :class="selectedHistory.winner === 'good' ? 'good' : 'evil'">
              <span class="winner-icon">{{ selectedHistory.winner === 'good' ? '🎉' : '💀' }}</span>
              <span class="winner-text">{{ selectedHistory.winner === 'good' ? '好人胜利' : '坏人胜利' }}</span>
            </div>
            <div class="detail-stats">
              <div class="stat-row">
                <span class="stat-label">玩家数：</span>
                <span class="stat-value">{{ selectedHistory.playerCount }}人</span>
              </div>
              <div class="stat-row">
                <span class="stat-label">成功任务：</span>
                <span class="stat-value success">{{ selectedHistory.successCount }}/5</span>
              </div>
              <div class="stat-row">
                <span class="stat-label">失败任务：</span>
                <span class="stat-value fail">{{ selectedHistory.failCount }}/5</span>
              </div>
              <div class="stat-row">
                <span class="stat-label">游戏时间：</span>
                <span class="stat-value">{{ formatTime(selectedHistory.timestamp) }}</span>
              </div>
            </div>
          </div>
          <div class="detail-section">
            <h4>任务结果</h4>
            <div class="detail-quest-results">
              <div
                v-for="(result, index) in selectedHistory.questResults"
                :key="index"
                class="detail-quest-badge"
                :class="result ? 'success' : 'fail'"
              >任务 {{ index + 1 }}: {{ result ? '✅ 成功' : '❌ 失败' }}</div>
            </div>
          </div>
          <div class="detail-section">
            <h4>玩家身份</h4>
            <div class="detail-players">
              <div v-for="player in selectedHistory.players" :key="player.id" class="detail-player-item" :class="isGoodRole(player.role) ? 'good' : 'evil'">
                <span class="player-name">{{ player.name }}</span>
                <span class="player-role">{{ player.role }}</span>
                <span class="player-side">{{ isGoodRole(player.role) ? '好人阵营' : '坏人阵营' }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 创建房间 - 输入名字 -->
    <div v-if="!room && step === 'create'" class="input-view">
      <h2>创建房间</h2>
      <div class="input-form">
        <input v-model="playerName" placeholder="请输入您的名字" @keyup.enter="handleCreateRoom" ref="nameInput" class="name-input" />
        <div class="form-buttons">
          <button @click="handleCreateRoom" :disabled="!playerName.trim()" class="confirm-btn">确认创建</button>
          <button @click="backToMenu" class="cancel-btn">返回</button>
        </div>
        <div v-if="error" class="error">{{ error }}</div>
      </div>
    </div>

    <!-- 加入房间 - 输入名字和房间代码 -->
    <div v-if="!room && step === 'join'" class="input-view">
      <h2>加入房间</h2>
      <div class="input-form">
        <input v-model="playerName" placeholder="请输入您的名字" @keyup.enter="handleJoinRoom" class="name-input" />
        <input v-model="joinRoomId" placeholder="请输入房间代码" @keyup.enter="handleJoinRoom" class="room-id-input" />
        <div class="form-buttons">
          <button @click="handleJoinRoom" :disabled="!playerName.trim() || !joinRoomId.trim()" class="confirm-btn">确认加入</button>
          <button @click="backToMenu" class="cancel-btn">返回</button>
        </div>
        <div v-if="error" class="error">{{ error }}</div>
      </div>
    </div>

    <!-- 房间等待界面 -->
    <div v-else-if="room" class="room-view">
      <h2>房间: {{ room.id }}</h2>
      <div class="room-code">{{ room.id }}</div>

      <!-- 房主设置游戏人数 -->
      <div v-if="socket && socket.id === room.host" class="player-count-setting">
        <h3>设置游戏人数</h3>
        <div class="flex" style="justify-content: center; flex-wrap: wrap; margin: 15px 0;">
          <button v-for="count in [5, 6, 7, 8, 9, 10]" :key="count" @click="setPlayerCount(count)" :class="{ active: room.requiredPlayerCount === count }" class="count-btn">{{ count }}人</button>
        </div>
      </div>

      <!-- 显示角色配置（所有人可见） -->
      <div v-if="currentRoleConfig" class="role-config">
        <div class="role-config-header">
          <h4>{{ currentRoleConfig.goodCount + currentRoleConfig.evilCount }}人游戏配置</h4>
        </div>
        <div class="role-config-content">
          <div class="team-section good-team">
            <h5>🛡️ 好人阵营 ({{ currentRoleConfig.goodCount }}人)</h5>
            <div class="role-cards">
              <div v-for="roleName in currentRoleConfig.goodRoles" :key="roleName" class="role-card good" :title="getRoleInfo(roleName)?.description">
                <div class="role-icon">{{ getRoleInfo(roleName)?.icon || '👤' }}</div>
                <div class="role-name">{{ roleName }}</div>
              </div>
            </div>
          </div>
          <div class="team-section evil-team">
            <h5>⚔️ 坏人阵营 ({{ currentRoleConfig.evilCount }}人)</h5>
            <div class="role-cards">
              <div v-for="roleName in currentRoleConfig.evilRoles" :key="roleName" class="role-card evil" :title="getRoleInfo(roleName)?.description">
                <div class="role-icon">{{ getRoleInfo(roleName)?.icon || '👤' }}</div>
                <div class="role-name">{{ roleName }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="player-list">
        <h3>玩家列表 ({{ room.players?.length || 0 }}{{ room.requiredPlayerCount ? '/' + room.requiredPlayerCount : '/10' }})</h3>
        <div v-for="player in room.players" :key="player.id" class="player-item" :class="{ ready: player.isReady }">
          <span>{{ player.name }} {{ player.id === room.host ? '(房主)' : '' }}</span>
          <span>{{ player.isReady ? '✓ 已准备' : '等待中' }}</span>
        </div>
      </div>

      <div v-if="socket && socket.id === room.host" class="mt-20">
        <div style="display: flex; gap: 10px; align-items: center; flex-wrap: wrap;">
          <button @click="toggleReady" style="flex: 1; min-width: 120px;">{{ isReady ? '✓ 已准备' : '点击准备' }}</button>
          <button @click="startGame" :disabled="!canStartGame" style="flex: 1; min-width: 120px;">开始游戏</button>
        </div>
        <div v-if="!canStartGame" style="margin-top: 10px; padding: 10px; background: #fff3cd; border-radius: 8px; border-left: 4px solid #ffc107;">
          <span style="color: #856404; font-size: 14px;">{{ startGameHint }}</span>
        </div>
      </div>
      <div v-else class="mt-20">
        <button @click="toggleReady">{{ isReady ? '✓ 已准备' : '点击准备' }}</button>
      </div>

      <div v-if="error" class="error">{{ error }}</div>
      <div v-if="success" class="success">{{ success }}</div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from "vue";
import { useRouter } from "vue-router";
import { useSocket } from "../composables/useSocket.js";
import { getRoleInfo } from "../roles.js";

export default {
  name: "RoomPage",
  setup() {
    const router = useRouter();
    const { socket, connect, disconnect } = useSocket();

    const playerName = ref("");
    const joinRoomId = ref("");
    const room = ref(null);
    const roleConfig = ref(null);
    const isReady = ref(false);
    const error = ref("");
    const success = ref("");
    const step = ref("menu"); // 'menu', 'create', 'join', 'history'
    const nameInput = ref(null);

    // 游戏历史记录
    const gameHistory = ref([]);
    const loadingHistory = ref(false);
    const selectedHistory = ref(null);

    const currentRoleConfig = computed(() => {
      return room.value?.roleConfig || roleConfig.value;
    });

    const canStartGame = computed(() => {
      if (!room.value || !room.value.players) return false;
      const playerCount = room.value.players.length;

      if (room.value.requiredPlayerCount) {
        if (playerCount !== room.value.requiredPlayerCount) return false;
      } else {
        if (playerCount < 5 || playerCount > 10) return false;
      }

      return room.value.players.every((p) => p.isReady);
    });

    const startGameHint = computed(() => {
      if (!room.value || !room.value.players) return "等待房间信息...";
      const playerCount = room.value.players.length;
      const readyCount = room.value.players.filter((p) => p.isReady).length;

      if (room.value.requiredPlayerCount) {
        if (playerCount !== room.value.requiredPlayerCount) {
          return `需要 ${room.value.requiredPlayerCount} 人，当前 ${playerCount} 人`;
        }
      } else {
        if (playerCount < 5) {
          return `至少需要 5 人才能开始，当前 ${playerCount} 人`;
        }
        if (playerCount > 10) {
          return `最多支持 10 人，当前 ${playerCount} 人`;
        }
      }

      if (readyCount < playerCount) {
        return `等待玩家准备 (${readyCount}/${playerCount})`;
      }

      return "可以开始游戏";
    });

    const listenersSetup = ref(false);

    function initSocket() {
      // Socket 连接在需要时才建立
      if (socket.value) {
        setupSocketListeners();
      }
    }

    function setupSocketListeners() {
      if (!socket.value || listenersSetup.value) return;
      listenersSetup.value = true;

      socket.value.on("roomCreated", (data) => {
        room.value = data.room;
        step.value = "menu"; // 重置步骤
        localStorage.setItem("currentRoomId", data.room.id);
        error.value = "";
        success.value = "房间创建成功！";
        setTimeout(() => (success.value = ""), 3000);
      });

      socket.value.on("joinedRoom", (data) => {
        room.value = data.room;
        step.value = "menu"; // 重置步骤
        localStorage.setItem("currentRoomId", data.room.id);
        error.value = "";
        success.value = "成功加入房间！";
        setTimeout(() => (success.value = ""), 3000);
      });

      socket.value.on("joinRoomError", (message) => {
        error.value = message;
      });

      socket.value.on("roomUpdated", (updatedRoom) => {
        room.value = updatedRoom;
        isReady.value =
          updatedRoom.players.find((p) => p.id === socket.value.id)?.isReady ||
          false;
        if (updatedRoom.roleConfig) {
          roleConfig.value = updatedRoom.roleConfig;
        }
      });

      socket.value.on("gameStarted", (data) => {
        // 跳转到游戏页面，通过路由state传递数据
        router.push({
          name: "game",
          state: { room: data.room, roleInfo: data.roleInfo },
        });
      });

      socket.value.on("error", (message) => {
        error.value = message;
        setTimeout(() => (error.value = ""), 5000);
      });

      socket.value.on("playerCountSet", (data) => {
        room.value = data.room;
        roleConfig.value = data.roleConfig;
        success.value = `已设置 ${data.count} 人游戏`;
        setTimeout(() => (success.value = ""), 3000);
      });

      socket.value.on("gameHistory", (history) => {
        gameHistory.value = history;
        loadingHistory.value = false;
      });
    }

    function showCreateForm() {
      step.value = "create";
      playerName.value = "";
      error.value = "";
      // 等待DOM更新后聚焦输入框
      setTimeout(() => {
        if (nameInput.value) {
          nameInput.value.focus();
        }
      }, 100);
    }

    function showJoinForm() {
      step.value = "join";
      playerName.value = "";
      joinRoomId.value = "";
      error.value = "";
    }

    function backToMenu() {
      step.value = "menu";
      playerName.value = "";
      joinRoomId.value = "";
      error.value = "";
      selectedHistory.value = null;
    }

    function showHistory() {
      step.value = "history";
      loadingHistory.value = true;
      gameHistory.value = [];

      // 确保socket连接
      if (!socket.value) {
        connect();
      }

      // 等待socket连接后请求历史记录
      const requestHistory = () => {
        if (socket.value && socket.value.connected) {
          socket.value.emit("getGameHistory");
        } else if (socket.value) {
          socket.value.once("connect", () => {
            socket.value.emit("getGameHistory");
          });
        } else {
          setTimeout(requestHistory, 100);
        }
      };

      requestHistory();
    }

    function formatTime(timestamp) {
      if (!timestamp) return "未知时间";
      const date = new Date(timestamp);
      const now = new Date();
      const diff = now - date;
      const minutes = Math.floor(diff / 60000);
      const hours = Math.floor(diff / 3600000);
      const days = Math.floor(diff / 86400000);

      if (minutes < 1) return "刚刚";
      if (minutes < 60) return `${minutes}分钟前`;
      if (hours < 24) return `${hours}小时前`;
      if (days < 7) return `${days}天前`;

      return date.toLocaleString("zh-CN", {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
      });
    }

    function isGoodRole(role) {
      if (!role) return false;
      const goodRoles = ["梅林", "派西维尔", "忠臣"];
      return goodRoles.includes(role);
    }

    function showHistoryDetail(record) {
      selectedHistory.value = record;
    }

    function closeHistoryDetail() {
      selectedHistory.value = null;
    }

    function handleCreateRoom() {
      if (!playerName.value.trim()) {
        error.value = "请输入您的名字";
        return;
      }
      error.value = "";

      // 确保socket连接
      if (!socket.value) {
        connect();
      }

      // 等待连接建立后再发送
      const tryEmit = () => {
        if (socket.value && socket.value.connected) {
          socket.value.emit("createRoom", playerName.value);
        } else if (socket.value) {
          // 如果socket存在但未连接，等待连接
          socket.value.once("connect", () => {
            socket.value.emit("createRoom", playerName.value);
          });
        } else {
          error.value = "连接失败，请重试";
        }
      };

      if (socket.value && socket.value.connected) {
        tryEmit();
      } else {
        setTimeout(tryEmit, 300);
      }
    }

    function handleJoinRoom() {
      if (!playerName.value.trim()) {
        error.value = "请输入您的名字";
        return;
      }
      if (!joinRoomId.value.trim()) {
        error.value = "请输入房间代码";
        return;
      }
      error.value = "";

      // 确保socket连接
      if (!socket.value) {
        connect();
      }

      // 等待连接建立后再发送
      const tryEmit = () => {
        if (socket.value && socket.value.connected) {
          socket.value.emit("joinRoom", {
            roomId: joinRoomId.value.toUpperCase(),
            playerName: playerName.value,
          });
        } else if (socket.value) {
          // 如果socket存在但未连接，等待连接
          socket.value.once("connect", () => {
            socket.value.emit("joinRoom", {
              roomId: joinRoomId.value.toUpperCase(),
              playerName: playerName.value,
            });
          });
        } else {
          error.value = "连接失败，请重试";
        }
      };

      if (socket.value && socket.value.connected) {
        tryEmit();
      } else {
        setTimeout(tryEmit, 300);
      }
    }

    function toggleReady() {
      if (!room.value || !socket.value) return;
      socket.value.emit("playerReady", { roomId: room.value.id });
    }

    function setPlayerCount(count) {
      if (!room.value || !socket.value) return;
      socket.value.emit("setPlayerCount", { roomId: room.value.id, count });
    }

    function startGame() {
      if (!room.value || !socket.value) return;
      socket.value.emit("startGame", { roomId: room.value.id });
    }

    onMounted(() => {
      // 监听socket连接，当连接建立后设置监听器
      watch(
        () => socket.value,
        (newSocket) => {
          if (newSocket) {
            // 如果socket已连接，立即设置监听器
            if (newSocket.connected) {
              setupSocketListeners();
            } else {
              // 否则监听connect事件
              newSocket.on("connect", () => {
                setupSocketListeners();
              });
            }
          }
        },
        { immediate: true }
      );
    });

    return {
      socket,
      playerName,
      joinRoomId,
      room,
      roleConfig,
      isReady,
      error,
      success,
      step,
      currentRoleConfig,
      canStartGame,
      startGameHint,
      showCreateForm,
      showJoinForm,
      backToMenu,
      handleCreateRoom,
      handleJoinRoom,
      toggleReady,
      setPlayerCount,
      startGame,
      getRoleInfo,
      nameInput,
      showHistory,
      formatTime,
      isGoodRole,
      showHistoryDetail,
      closeHistoryDetail,
      gameHistory,
      loadingHistory,
      selectedHistory,
    };
  },
};
</script>

